from datetime import datetime

from flask import Flask, render_template, request, redirect, url_for, flash
from flask_migrate import Migrate

import config
from config import DB_URI
from exts import db
from models.forms import ScheduleForm, ModifyForm
from models.todo import ToDoModel

app = Flask(__name__)
app.config.from_object(config)
app.config['SQLALCHEMY_DATABASE_URI'] = DB_URI
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)
migrate = Migrate(app, db)


def get_date_weekday():
    date = datetime.now().strftime('%Y年%m月%d日')
    week = datetime.weekday(datetime.now())
    week_name = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日']
    week_day = week_name[week]
    date_week = f'{date} {week_day}'
    return date_week


@app.route('/', methods=['GET', 'POST'])
def index():
    week = get_date_weekday()
    todo_list = ToDoModel.query.order_by(db.text('-id')).all()  # 这个排序法很重要
    return render_template('index.html', todo_list=todo_list, week=week)


@app.route('/upload', methods=['GET', 'POST'])
def upload_data():
    if request.method == 'GET':
        return redirect(url_for('index'))
    else:
        form = ScheduleForm(request.form)
        if form.validate():
            deadline = form.deadline.data
            content = form.content.data
            todo_data = ToDoModel(deadline=deadline, content=content)
            db.session.add(todo_data)
            db.session.commit()
            return redirect(url_for('index'))
        else:
            flash('项目填写不完全，请核对后再次填写！！！')
            return redirect(url_for('upload_data'))


@app.route('/modify', methods=['GET', 'POST'])
def modify():
    week = get_date_weekday()
    id = request.args.get('id')
    form = ModifyForm(request.form)
    schedule = ToDoModel.query.filter_by(id=id).first()
    if form.validate():
        deadline = form.deadline.data
        content = form.content.data
        schedule.deadline = deadline
        schedule.content = content
        db.session.commit()
        return redirect(url_for('index'))
    return render_template('modify.html', schedule=schedule, week=week)


@app.route('/delete', methods=['GET'])
def delete():
    id = request.args.get('id')
    ToDoModel.query.filter_by(id=id).delete()
    db.session.commit()
    return redirect(url_for('index'))


if __name__ == '__main__':
    app.run()
